package com.vip.oauth2.security;

import com.vip.oauth2.constant.AuthConsts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import java.util.concurrent.TimeUnit;

/**
 * 认证授权服务配置：配置授权服务需要的基础参数
 *
 * @author wgb
 * @date 2020/3/21 17:09
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTokenStore redisTokenStore;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode(AuthConsts.CLIENT_SECRET);
        //配置客户端，使用密码模式验证鉴权
        clients.inMemory()
              .withClient(AuthConsts.CLIENT_ID)
              //密码模式及refresh_token模式
              .authorizedGrantTypes(AuthConsts.GRANT_TYPE[0], AuthConsts.GRANT_TYPE[1])
              .scopes("all")
              .secret(finalSecret);
    }

    /**
     * token及用户信息存储到redis，当然你也可以存储在当前的服务内存，不推荐
     *
     * @param endpoints
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        /**
         * token信息存到redis
         */
        endpoints.tokenStore(redisTokenStore).authenticationManager(authenticationManager);
        //配置TokenService参数
        DefaultTokenServices tokenService = new DefaultTokenServices();
        tokenService.setTokenStore(endpoints.getTokenStore());
        tokenService.setSupportRefreshToken(true);
        tokenService.setClientDetailsService(endpoints.getClientDetailsService());
        tokenService.setTokenEnhancer(endpoints.getTokenEnhancer());
        //1小时
        tokenService.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1));
        //1小时
        tokenService.setRefreshTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(1));
        tokenService.setReuseRefreshToken(false);
        endpoints.tokenServices(tokenService);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        //允许表单认证
        oauthServer.allowFormAuthenticationForClients().tokenKeyAccess("isAuthenticated()").checkTokenAccess("permitAll()");
    }
}
